<template>
    <div class="select">
        <div v-if="initloading" class="select-loading">
            <el-icon class="is-loading"><el-icon-loading /></el-icon>
        </div>
        <el-select
            ref="select"
            v-model="defaultValue"
            :size="size"
            :clearable="clearable"
            :multiple="multiple"
            :collapse-tags="collapseTags"
            :collapse-tags-tooltip="collapseTagsTooltip"
            :filterable="filterable"
            :placeholder="placeholder"
            :disabled="disabled"
            @remove-tag="removeTag"
            @visible-change="visibleChange"
            @clear="clear"
        >
            <template #empty>
                <div class="user-select">
                    <div class="user-select__left">
                        <div class="user-select__search">
                            <el-input v-model="keyword" clearable prefix-icon="el-icon-search" placeholder="搜索成员">
                                <template #append>
                                    <el-button icon="el-icon-search" @click="search"></el-button>
                                </template>
                            </el-input>
                        </div>
                        <div class="user-select__select">
                            <div class="user-select__tree" v-loading="showGrouploading">
                                <el-scrollbar>
                                    <el-tree class="menu" ref="groupTree" :data="group" :node-key="groupProps.key" :props="groupProps" highlight-current :expand-on-click-node="false" :default-expand-all="true" :current-node-key="groupId" @node-click="groupClick" />
                                </el-scrollbar>
                            </div>
                            <div class="user-select__user" v-loading="showUserloading">
                                <div class="user-select__user__list">
                                    <el-scrollbar ref="userScrollbar">
                                        <!-- <el-tree class="menu" ref="userTree" :data="user" :node-key="userProps.key" :props="userProps" :default-checked-keys="selectedIds" show-checkbox check-on-click-node @check-change="userClick"></el-tree> -->
                                        <el-tree class="menu" ref="userTree" :data="user" :node-key="userProps.key" :props="userPropsWithDisabled" :default-checked-keys="selectedIds" show-checkbox check-on-click-node @check-change="userClick"></el-tree>
                                    </el-scrollbar>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="user-select__toicon">
                        <el-icon><el-icon-arrow-right /></el-icon>
                    </div>
                    <div class="user-select__selected">
                        <header>已选 ({{ selected.length }})</header>
                        <ul style="padding-top: 5px">
                            <el-scrollbar>
                                <li v-for="(item, index) in selected" :key="item.id">
                                    <span class="name">
                                        <el-avatar size="small">{{ item.name.substring(0, 1) }}</el-avatar>
                                        <label>{{ item.name }}</label>
                                    </span>
                                    <span class="delete">
                                        <el-button type="danger" icon="el-icon-delete" circle size="small" @click="deleteSelected(index)"></el-button>
                                    </span>
                                </li>
                            </el-scrollbar>
                        </ul>
                    </div>
                </div>
                <div class="user-select__footer">
                    <el-button @click="cancel">取 消</el-button>
                    <el-button type="primary" @click="save">确 定</el-button>
                </div>
            </template>
        </el-select>
    </div>
</template>

<script>
import config from '@/config/workflow';

export default {
    props: {
        modelValue: null,
        apiObj: { type: Object, default: () => {} },
        params: { type: Object, default: () => {} },
        placeholder: { type: String, default: '请选择' },
        size: { type: String, default: 'default' },
        clearable: { type: Boolean, default: false },
        multiple: { type: Boolean, default: false },
        filterable: { type: Boolean, default: false },
        collapseTags: { type: Boolean, default: false },
        collapseTagsTooltip: { type: Boolean, default: false },
        disabled: { type: Boolean, default: false },
        tableWidth: { type: Number, default: 400 },
        mode: { type: String, default: 'popover' },
        props: { type: Object, default: () => {} }
    },
    data() {
        return {
            initloading: false,
            loading: false,
            deptId: null,
            depts: [],
            members: [],
            options: [],
            value: [],

            groupProps: config.group.props,
            userProps: config.user.props,

            roleProps: {
                key: 'roleId',
                label: 'roleName'
            },
            titleMap: ['人员选择', '角色选择'],
            dialogVisible: false,
            showGrouploading: false,
            showUserloading: false,
            keyword: '',
            groupId: '',
            pageSize: 10,
            total: 0,
            currentPage: 1,
            searchForm: {},
            group: [],
            user: [],
            role: [],
            type: 1,
            selected: [],
            defaultRoleGroup: 1,
            roleGroup: [
                { label: '系统角色', value: 1 },
                { label: '应用角色', value: 2 }
            ],
            defaultValue: [],
            defaultProps: {
                label: 'name',
                value: 'id'
            }
        };
    },
    created() {
        //如果有默认值就去请求接口获取options
        if (this.$attrs.modelValue && this.$attrs.modelValue.length > 0) {
            this.initloading = true;
            this.getGroup();
            this.getUser();
        }
    },
    computed: {
        selectedIds() {
            return this.selected.map((t) => t.id);
        },
        selectedId() {
            const result = (this.selected && this.selected[0]?.id) || null;
            return result;
        },
        userPropsWithDisabled() {
            return {
                key: 'id',
                label: 'name',
                disabled: (data) => {
                    if (this.multiple === false) {
                        if (this.selectedId == null) {
                            return false;
                        } else if (data.id === this.selectedId) {
                            return false;
                        } else {
                            return true;
                        }
                    } else {
                        return false;
                    }
                }
            };
        }
    },
    watch: {
        modelValue: {
            handler() {
                this.defaultValue = this.modelValue;
                // this.defaultValue = this.convertModelValue(this.modelValue);
                this.autoCurrentLabel();
            },
            deep: true
        }
    },
    mounted() {
        this.defaultValue = this.modelValue;
        // this.defaultValue = this.convertModelValue(this.modelValue);
        this.autoCurrentLabel();
    },
    methods: {
        // 转换modelValue的结构为符合select组件的结构
        convertModelValue(modelValue) {
            let result;
            if (Array.isArray(this.modelValue)) {
                result = modelValue.map((item) => {
                    return {
                        label: item[this.userProps.label],
                        value: item[this.userProps.key]
                    };
                });
            }
            return result;
        },
        convertDefaultValue(defaultValue) {
            console.log(defaultValue);
            let result;
            if (Array.isArray(defaultValue)) {
                result = defaultValue.map((item) => {
                    return {
                        [this.userProps.label]: item.label,
                        [this.userProps.key]: item.value
                    };
                });
            } else {
                result = [
                    {
                        [this.userProps.label]: defaultValue.label,
                        [this.userProps.key]: defaultValue.value
                    }
                ];
            }
            return result;
        },
        //选项显示隐藏事件
        visibleChange(ispoen) {
            // if(ispoen && this.options.length==0 && (this.dict || this.apiObj)){

            // }
            this.getGroup();
            this.getUser();
            if (!ispoen) {
                this.autoCurrentLabel();
                // this.defaultValue ? (this.selected = [...this.defaultValue]) : (this.selected = []);
                this.defaultValue ? (this.selected = this.convertDefaultValue(this.defaultValue)) : (this.selected = []);
            }
        },
        //自动模拟options赋值
        autoCurrentLabel() {
            this.$nextTick(() => {
                if (this.defaultValue == null) return;
                this.$nextTick(() => {
                    if (this.multiple) {
                        this.$refs.select.selectedLabel = this.defaultValue.map((item) => item[this.defaultProps.label]);
                    } else {
                        // this.$refs.select.selectedLabel = this.defaultValue[0][this.defaultProps.label];
                        this.$refs.select.selectedLabel = this.defaultValue.label;
                    }
                });
            });
        },
        //获取组织
        async getGroup() {
            this.showGrouploading = true;
            var res = await this.$API.system.dept.tree.get();
            this.showGrouploading = false;
            //var allNode = {[config.group.props.key]: '', [config.group.props.label]: '所有'}
            //res.data.unshift(allNode);
            this.group = config.group.parseData(res).rows;
        },
        //获取用户
        async getUser() {
            this.showUserloading = true;
            let res = await this.$API.system.member.getMemberByDept.list.get(this.searchForm);
            if (res.code == 200) {
                this.user = res.data.rows;
                this.total = res.data.total;
                this.$refs.userScrollbar.setScrollTop(0);
            }
            this.showUserloading = false;
        },
        //获取角色
        async getRole() {
            this.showGrouploading = true;
            if (this.defaultRoleGroup == 1) {
                this.searchForm.roleType = 1;
                let res = await this.$API.system.role.list.get(this.searchForm);
                if (res.code == 200) {
                    this.role = res.data.rows;
                    this.total = res.data.total;
                    this.$refs.roleScrollbar.setScrollTop(0);
                }
            } else {
                this.searchForm.appId = this.$route.query.appId;
                let res = await this.$API.app.roleGroup.list.get(this.searchForm);
                if (res.code == 200) {
                    this.role = [];
                    res.data.rows.map((item) => {
                        this.role.push({ roleId: item.id, roleName: item.groupName });
                    });
                    this.total = res.total;
                    this.$refs.roleScrollbar.setScrollTop(0);
                }
            }
            this.showGrouploading = false;
        },
        //组织点击
        groupClick(data) {
            // 名称
            this.searchForm.name = '';
            // 当前页码
            this.searchForm.pageNum = 1;
            // 页面大小
            this.searchForm.pageSize = this.pageSize;
            // 部门
            this.searchForm.deptId = data[config.group.props.key];
            this.getUser(this.searchForm);
        },
        // 角色组点击
        roleGroupClick(data) {
            // 当前页码
            this.searchForm.pageNum = 1;
            // 页面大小
            this.searchForm.pageSize = this.pageSize;
            this.defaultRoleGroup = data.value;
            this.selected = [];
            this.role = [];
            this.getRole();
        },
        //用户点击
        userClick(data, checked) {
            if (checked) {
                this.selected.push({
                    id: data[config.user.props.key],
                    name: data[config.user.props.label]
                });
            } else {
                this.selected = this.selected.filter((item) => item.id != data[config.user.props.key]);
            }
        },
        // 角色点击
        roleClick(data, checked) {
            if (checked) {
                this.selected.push({
                    id: data[this.roleProps.key],
                    name: data[this.roleProps.label],
                    group: this.defaultRoleGroup
                });
            } else {
                this.selected = this.selected.filter((item) => item.id != data[this.roleProps.key]);
            }
        },
        //用户分页点击
        paginationChange() {
            this.searchForm.pageNum = this.currentPage;
            if (this.type == 1) {
                this.getUser();
            } else {
                this.getRole();
            }
        },
        //用户搜索
        search() {
            // 名称
            this.searchForm.name = this.keyword;
            // 当前页码
            this.searchForm.pageNum = 1;
            // 页面大小
            this.searchForm.pageSize = this.pageSize;
            this.getUser(this.searchForm);
        },
        //删除已选
        deleteSelected(index) {
            this.selected.splice(index, 1);
            this.$refs.userTree.setCheckedKeys(this.selectedIds);
        },
        // 取消按钮
        cancel() {
            this.$refs.select.blur();
        },
        // 提交保存
        save() {
            this.defaultValue = [];
            this.defaultValue.splice(0, this.defaultValue.length);
            if (this.multiple) {
                this.selected.map((item) => {
                    // this.defaultValue.push(item);
                    this.defaultValue.push({
                        label: item[this.userProps.label],
                        value: item[this.userProps.key]
                    });
                });
            } else {
                this.defaultValue = {
                    label: this.selected[0][this.userProps.label],
                    value: this.selected[0][this.userProps.key]
                };
            }
            this.$emit('update:modelValue', this.defaultValue);
            this.autoCurrentLabel();
            this.$refs.select.blur();
        }
    }
};
</script>

<style scoped>
.select {
    display: inline-block;
    position: relative;
}
.select-loading {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: #fff;
    z-index: 100;
    border-radius: 5px;
    border: 1px solid #ebeef5;
    display: flex;
    align-items: center;
    padding-left: 10px;
}
.select-loading i {
    font-size: 14px;
}

.dark .select-loading {
    background: var(--el-bg-color-overlay);
    border-color: var(--el-border-color-light);
}
.jd-select__wrap {
    padding: 20px;
    max-width: 950px;
}
.item-box {
    display: inline-block;
    margin: 10px;
    width: 30px;
    height: 30px;
    font-size: 20px;
    line-height: 30px;
    background-color: #ccc;
    color: white;
    text-align: center;
    cursor: pointer;
    user-select: none;
}

.item-box1 {
    display: inline-block;
    margin: 10px;
    width: 30px;
    height: 30px;
    font-size: 20px;
    line-height: 30px;
    background-color: #ccc;
    color: black;
    outline: 0.5px solid black;
    text-align: center;
    cursor: pointer;
    user-select: none;
}

.item-box2 {
    display: inline-block;
    margin: 10px;
    width: 30px;
    height: 30px;
    font-size: 20px;
    line-height: 30px;
    background-color: white;
    outline: 0.5px solid black;
    color: black;
    text-align: center;
    cursor: pointer;
    user-select: none;
}

.car-number {
    font-size: 20px;
    font-weight: bolder;
    width: 230px;
    height: 40px;
    margin: 0 auto;
    background-color: darkblue;
    color: white;
    line-height: 40px;
    padding-left: 20px;
    border-radius: 5px;
    user-select: none;
}
.new-energy {
    background-color: #60bd81;
    width: 245px;
}

.backspace {
    display: inline-block;
    font-size: 20px;
    font-weight: bolder;
    height: 40px;
    line-height: 40px;
    text-align: center;
    margin-left: 10px;
    padding-left: 10px;
    padding-right: 10px;
    border-radius: 5px;
    border: 0.5px solid black;
    cursor: pointer;
    user-select: none;
}
.backspace-disabled {
    opacity: 0.5;
    cursor: not-allowed;
}
.backspace-disabled a:hover {
    color: #333;
}

.user-select {
    display: flex;
    padding: 15px;
}
.user-select__left {
    width: 400px;
}
.user-select__right {
    flex: 1;
}

.user-select__search {
    padding-bottom: 10px;
}

.user-select__select {
    display: flex;
    border: 1px solid var(--el-border-color-light);
    background: var(--el-color-white);
}
.user-select__tree {
    width: 200px;
    height: 300px;
    border-right: 1px solid var(--el-border-color-light);
}
.user-select__user {
    width: 200px;
    height: 300px;
    display: flex;
    flex-direction: column;
}
.user-select__user__list {
    flex: 1;
    overflow: auto;
}
.user-select__user footer {
    height: 36px;
    padding-top: 5px;
    border-top: 1px solid var(--el-border-color-light);
}

.user-select__toicon {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 10px;
}
.user-select__toicon i {
    display: flex;
    justify-content: center;
    align-items: center;
    background: #ccc;
    width: 20px;
    height: 20px;
    text-align: center;
    line-height: 20px;
    border-radius: 50%;
    color: #fff;
}

.user-select__selected {
    height: 345px;
    width: 200px;
    border: 1px solid var(--el-border-color-light);
    background: var(--el-color-white);
}
.user-select__selected header {
    height: 43px;
    line-height: 43px;
    border-bottom: 1px solid var(--el-border-color-light);
    padding: 0 15px;
    font-size: 12px;
}
.user-select__selected ul {
    height: 300px;
    overflow: auto;
}
.user-select__selected li {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 5px 5px 5px 15px;
    height: 38px;
}
.user-select__selected li .name {
    display: flex;
    align-items: center;
}
.user-select__selected li .name .el-avatar {
    background: #409eff;
    margin-right: 10px;
}
.user-select__selected li .name label {
}
.user-select__selected li .delete {
    display: none;
    padding-right: 5px;
}
.user-select__selected li:hover {
    background: var(--el-color-primary-light-9);
}
.user-select__selected li:hover .delete {
    display: inline-block;
    padding-right: 5px;
}

.user-select-role .user-select__left {
    width: 200px;
}
.user-select-role .user-select__tree {
    border: none;
    height: 343px;
}
.user-select-role .user-select__selected {
}

[data-theme='dark'] .user-select__selected li:hover {
    background: rgba(0, 0, 0, 0.2);
}
[data-theme='dark'] .user-select__toicon i {
    background: #383838;
}

.user-select__footer {
    padding: 15px;
    padding-top: 0px;
    text-align: right;
}
</style>
